package com.kirin.web.server;

import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * Created by gong.libin on 2018/01/01.
 * 自定义拦截器（如对用户操作权限等的控制）
 */
public class KrnInterceptor implements HandlerInterceptor {
    /**
     * 该方法将在请求处理之前被调用，只有该方法返回true，才会继续
     * 执行后续的Interceptor和Controller，当返回值为true时就会
     * 继续调用下一个Interceptor的preHandle方法，如果已经是最后
     * 一个Interceptor的时候就会是调用当前请求的Controller方法。
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        boolean rst = true;
        String err = "{\"code\":500,\"message\":\"操作错误\",\"data\":null}";

        if (true != httpServletRequest.getMethod().equals("GET")) {
            httpServletResponse.setCharacterEncoding("UTF-8");
            httpServletResponse.setContentType("text/html; charset=utf-8");

            try {
                PrintWriter writer = httpServletResponse.getWriter();
                writer.print(err);
                writer.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            rst = false;
        }

        return rst;
    }

    /**
     * 该方法将在请求处理之后，DispatcherServlet进行视图
     * 返回渲染之前进行调用，可以在这个方法中对Controller
     * 处理之后的ModelAndView 对象进行操作。
     */
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    }

    /**
     * 该方法也是需要当前对应的Interceptor的preHandle方法的返回值为true
     * 时才会执行，该方法将在整个请求结束之后，也就是在DispatcherServlet
     * 渲染了对应的视图之后执行。用于进行资源清理。
     */
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
    }
}